package com.hopedove.productionworkshop

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.databinding.DataBindingUtil
import com.hopedove.base.BaseActivity
import com.hopedove.productionworkshop.databinding.ActivityMainBinding
import com.hopedove.view.SimpleDialog
import com.zhuyu.downloadlibrary.DownloadDialog
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.io.File

class MainActivity : BaseActivity() {
    private lateinit var binding: ActivityMainBinding
    private val viewModel: AppHomePageViewModel by viewModel()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        binding.vm = viewModel
        setupViewModel()
        viewModel.load()
    }

    private fun setupViewModel() {
        viewModel.navigation.observe(this, { dest ->
            startActivity(Intent(this, dest))
        })

        viewModel.updateInfo.observe(this, { info ->
            showUpgradeDialog(info.force, info.url, info.downloadPath)
        })
    }

    private fun showUpgradeDialog(_force: Boolean, _url: String, _filePath: String) {
        val showDownload: ((Boolean, String, String) -> Unit) = { force, url, filePath ->
            val dowDialog = DownloadDialog.newInstance(url, filePath, force)
            dowDialog.setDownloadListener(object : DownloadDialog.DownloadSimpleListener {
                override fun onSuccess() {
                    launchInstallApkActivity(filePath)
                }

                override fun onError() {
                    Toast.makeText(baseContext, R.string.download_fail, Toast.LENGTH_SHORT).show()
                }
            })
            dowDialog.show(supportFragmentManager, "DownLoad")
        }

        if (_force) {
            SimpleDialog.forceShow(this,
                resources.getString(R.string.application_has_new_version_need_force_update),
                SimpleDialog.OnPositiveClickListener {
                    showDownload(_force, _url, _filePath)
                })
        } else {
            SimpleDialog.show(this,
                resources.getString(R.string.application_has_new_version_need_update),
                SimpleDialog.OnPositiveClickListener {
                    showDownload(_force, _url, _filePath)
                })
        }
    }

    private fun launchInstallApkActivity(filePath: String) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val contentUri = FileProvider.getUriForFile(
                this,
                "${BuildConfig.APPLICATION_ID}.provider",
                File(filePath)
            )

            val install = Intent(Intent.ACTION_INSTALL_PACKAGE)
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            install.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            install.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
            install.data = contentUri
            startActivity(install)
        } else {
            val apkUri = Uri.fromFile(File(filePath))
            val install = Intent(Intent.ACTION_VIEW)
            install.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
            install.setDataAndType(
                apkUri,
                "application/vnd.android.package-archive"
            )
            startActivity(install)
        }
    }
}